from django.shortcuts import render, get_object_or_404, redirect
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q
from .models import Post, Category, Comment
from .forms import PostForm, CommentForm


def post_list(request):
    """文章列表视图"""
    posts = Post.objects.filter(status='published').order_by('-published_at')
    
    # 搜索功能
    search_query = request.GET.get('search')
    if search_query:
        posts = posts.filter(
            Q(title__icontains=search_query) | 
            Q(content__icontains=search_query) |
            Q(excerpt__icontains=search_query)
        )
    
    # 分类筛选
    category_id = request.GET.get('category')
    if category_id:
        posts = posts.filter(category_id=category_id)
    
    # 分页
    paginator = Paginator(posts, 5)  # 每页显示5篇文章
    page_number = request.GET.get('page')
    posts = paginator.get_page(page_number)
    
    # 获取所有分类
    categories = Category.objects.all()
    
    context = {
        'posts': posts,
        'categories': categories,
        'search_query': search_query,
        'selected_category': category_id,
    }
    return render(request, 'blog/post_list.html', context)


def post_detail(request, slug):
    """文章详情视图
    允许作者或管理员查看未发布文章；其他用户仅可查看已发布文章。
    """
    post = get_object_or_404(Post, slug=slug)
    # 若文章未发布，仅作者本人或管理员可见
    if post.status != 'published':
        if not request.user.is_authenticated:
            raise Http404()
        if not (request.user == post.author or request.user.is_staff):
            raise Http404()
    
    # 增加浏览次数
    post.views += 1
    post.save(update_fields=['views'])
    
    # 获取相关文章（同分类的其他文章，仅展示已发布）
    related_posts = Post.objects.filter(
        category=post.category,
        status='published'
    ).exclude(id=post.id)[:3]
    
    # 获取评论
    comments = post.comments.filter(is_approved=True).order_by('-created_at')
    
    # 处理评论提交
    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.save()
            messages.success(request, '评论提交成功！')
            return redirect('blog:post_detail', slug=post.slug)
    else:
        comment_form = CommentForm()
    
    context = {
        'post': post,
        'related_posts': related_posts,
        'comments': comments,
        'comment_form': comment_form,
    }
    return render(request, 'blog/post_detail.html', context)


@login_required
def post_create(request):
    """创建文章视图"""
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            messages.success(request, '文章创建成功！')
            return redirect('blog:post_detail', slug=post.slug)
    else:
        form = PostForm()
    
    return render(request, 'blog/post_form.html', {'form': form, 'title': '创建文章'})


@login_required
def post_edit(request, slug):
    """编辑文章视图"""
    post = get_object_or_404(Post, slug=slug, author=request.user)
    
    if request.method == 'POST':
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            form.save()
            messages.success(request, '文章更新成功！')
            return redirect('blog:post_detail', slug=post.slug)
    else:
        form = PostForm(instance=post)
    
    return render(request, 'blog/post_form.html', {'form': form, 'title': '编辑文章', 'post': post})


@login_required
def my_posts(request):
    """我的文章列表"""
    posts = Post.objects.filter(author=request.user).order_by('-created_at')
    
    # 分页
    paginator = Paginator(posts, 10)
    page_number = request.GET.get('page')
    posts = paginator.get_page(page_number)
    
    return render(request, 'blog/my_posts.html', {'posts': posts})


def category_posts(request, category_id):
    """分类文章列表"""
    category = get_object_or_404(Category, id=category_id)
    posts = Post.objects.filter(category=category, status='published').order_by('-published_at')
    
    # 分页
    paginator = Paginator(posts, 5)
    page_number = request.GET.get('page')
    posts = paginator.get_page(page_number)
    
    context = {
        'category': category,
        'posts': posts,
    }
    return render(request, 'blog/category_posts.html', context)